// ====================CardDeck====================

class Sprite_CardDeck extends CardContainerBase {
    initialize() {
        this._value = NaN;
        this._focusState = null;
        this.createAllSprite();
    }

    createAllSprite() {
        this.createCardBackSprite();
        this.createAmountSprite();
    }

    createCardBackSprite() {
        const {width, height, iconSize, iconIndex, deckFile} = this._opts;
        const bitmap = new Bitmap(width, height);
        const sprite = new Sprite(bitmap);
        const cardBackBitmap = ImageManager.loadSystem(deckFile);
        const ix = (width - iconSize) / 2;
        const iy = height / 2 - iconSize;
        cardBackBitmap.addLoadListener(() => {
            bitmap.blt(cardBackBitmap, 0, 0, cardBackBitmap.width, cardBackBitmap.height, 0, 0, width, height);
            bitmap.drawIcon(iconIndex, ix, iy, iconSize, iconSize);
        })
        this._cardBackSprite = sprite;
        this.addChild(sprite);
    }

    createAmountSprite() {
        const {width, height, fontSize} = this._opts;
        const w = 32;
        const h = 32;
        const x = (width - w) / 2;
        const y = height / 2;
        const bitmap = new Bitmap(w, h);
        const sprite = new Sprite(bitmap);
        bitmap.fontSize = fontSize;
        bitmap.fontFace = $gameSystem.mainFontFace();
        sprite.move(x, y);
        this._amountSprite = sprite;
        this.addChild(sprite);
    }

    updateContainer() {
        this.updateAmount();
        this.updateOpacity();
        this.updateClick();
    }

    updateAmount() {
        const {type} = this._opts;
        const object = type === "deck" ? CardGameManager.deck : CardGameManager.cemetery;
        if (object.length !== this._value) {
            this._value = object.length;
            this.drawAmount();
        }
    }

    updateOpacity() {
        const {width, height} = this._opts;
        const x = this.x;
        const y = this.y;
        const rect = new Rectangle(x, y, width, height);
        const state = rect.contains(TouchInput.x, TouchInput.y);
        if (state !== this._focusState) {
            if (state === true) {
                this.alpha = 0.5;
            } else {
                this.alpha = 1;
            }
        }
        this._focusState = state;
    }

    updateClick() {
        if(TouchInput.isClicked() && this._focusState) {
            const {type} = this._opts;
            if(type === "deck") {
                CardGameManager.displayDeck();
            } else if(type === "cemetery") {
                CardGameManager.displayCemetery();
            }
        }
    }

    drawAmount() {
        const bitmap = this._amountSprite.bitmap;
        bitmap.clear();
        bitmap.fillRoundRect(0, 0, bitmap.width, bitmap.height, "#b7b4b4", 0);
        bitmap.drawText(this._value, 0, 0, bitmap.width, bitmap.height, "center");
    }
}